// 和用户相关的状态管理

import { createSlice } from "@reduxjs/toolkit";
import { request,setToken as _setToken,getToken, removeToken } from "../../utils";
import { getUserInfoAPI, loginAPI } from "../../apis/user";

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo:{}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
          _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state,action){
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})


// 解构actionCreator

const { setToken,setUserInfo,clearUserInfo } = userStore.actions

// 获取reducer函数

const userReducer = userStore.reducer

// 登录
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        const res = await loginAPI(loginForm)
        console.log("登录注册", res);
        dispatch(setToken(res.data.token))
    }
}

// 获取个人用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfoAPI()
        dispatch(setUserInfo(res.data))
    }
}

export { setToken,fetchUserInfo, fetchLogin,clearUserInfo }

export default userReducer